//
//  NSPrivatePhotoBrowser.m
//  Meboo
//
//  Created by kyo on 2024/5/28.
//

#import "NSPrivatePhotoBrowser.h"
#import "GXPHKitTool.h"
#import "FirebaseCore/FirebaseCore.h"
#import "FirebaseStorage/FirebaseStorage-Swift.h"
#import "NSVipPopView.h"
@interface NSPrivatePhotoBrowser ()
@property (nonatomic, strong) UIView *topBackView;
@property (nonatomic, strong) UIButton *closeBtn;

@property (nonatomic, strong) UIView *bottomBackView;
@property (nonatomic, strong) UIButton *sendBtn;

@property (nonatomic, strong) NSData *data;
//视频大小
@property (nonatomic, assign) CGFloat videoSize;

//记录失败次数 记录重试次数 6次超时
@property (nonatomic, assign) NSInteger sendTimes;

//防截屏
@property (nonatomic, strong) UIView *secView;
@end

@implementation NSPrivatePhotoBrowser

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self creatSubViews];
}

#pragma mark - Send Private Action
- (NSString *)getTimeNow {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss SSS"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]*1000];
    
    int randomNumber = arc4random_uniform(9000) + 1000;
    NSLog(@"随机数：%d", randomNumber);
    
    timeSp = [NSString stringWithFormat:@"%@%d",timeSp,randomNumber];
    
    return timeSp;
}

- (void)putUploadImageOrVideo:(BOOL)isVideo {
    
    NSString *imageStr = @"images4";
    if (self.sendTimes % 2 == 0) {
        imageStr = @"images4";
    } else {
        imageStr = @"images5";
    }
    __WeakSelf
    // Get a reference to the storage service using the default Firebase App
    FIRStorage *storage = [FIRStorage storage];
    
    // Create a storage reference from our storage service
    FIRStorageReference *storageRef = [storage reference];
    
    FIRStorageMetadata *metadata = [[FIRStorageMetadata alloc] init];
    metadata.contentType = @"image/jpeg";
    
    // Data in memory
    NSData *data = UIImageJPEGRepresentation(self.curPhotoView.imageView.image, 1);
    //image/jpeg
    // Create a reference to the file you want to upload
    FIRStorageReference *riversRef;
    riversRef = [storageRef child:[NSString stringWithFormat:@"%@/PrivatePhoto%@.jpeg",imageStr,[self getTimeNow]]];
    if (isVideo) {
        metadata.contentType = @"video/mp4";
        riversRef = [storageRef child:[NSString stringWithFormat:@"%@/PrivateVideo%@.mp4",imageStr,[self getTimeNow]]];
    }
    
    // Upload the file to the path "images/rivers.jpg"
    FIRStorageUploadTask *uploadTask = [riversRef putData:isVideo ? self.data : data
                                                 metadata:metadata
                                               completion:^(FIRStorageMetadata *metadata,
                                                            NSError *error) {
        if (error != nil) {
            // Uh-oh, an error occurred!
            //          [MBNotificationCenter postNotificationName:REGISTER_UPLOADPHOTO_END object:nil];
            NSLog(@"%@",error);
            if (self.sendTimes >= 5) {
                [MBNotificationCenter postNotificationName:REGISTER_UPLOADPHOTO_FAIL object:nil];
                if (self.sendBlock) {
                    self.sendBlock(NO);
                }
                self.sendTimes = 0;
            }  else {
                self.sendTimes++;
                [self putUploadImageOrVideo:isVideo];
            }
        } else {
            self.sendTimes = 0;
            // Metadata contains file metadata such as size, content-type, and download URL.
            int size = metadata.size;
            // You can also access to download URL after upload.
            [riversRef downloadURLWithCompletion:^(NSURL * _Nullable URL, NSError * _Nullable error) {
                if (error != nil) {
                    // Uh-oh, an error occurred!
                    //              [MBNotificationCenter postNotificationName:REGISTER_UPLOADPHOTO_END object:nil];
                    NSLog(@"%@",error);
                    if (self.sendBlock) {
                        self.sendBlock(NO);
                    }
                } else {
                    NSURL *downloadURL = URL;
                    NSString *urlStr = [URL absoluteString];
                    NSLog(@"%@",urlStr);
                    
                    NSString *headerStr = @"/images";
                    NSRange widthRange1 = [urlStr rangeOfString:headerStr];//匹配得到的下标
                    urlStr = [urlStr substringFromIndex:widthRange1.location];
                    NSRange widthRange2 = [urlStr rangeOfString:@"?"];//匹配得到的下标
                    urlStr = [urlStr substringToIndex:widthRange2.location];
                    NSLog(@"");
                    [[MBChatDataManager sharedManager] sendPrivatePhoteWithImageUrl:urlStr type:3 videoLength:self.videoLength success:^(BOOL success) {
                        if (success) {
                            [MBNotificationCenter postNotificationName:REGISTER_UPLOADPHOTO_END object:nil];
                        }
                    }];
                    if (self.videoLength > 0) {
                        if (![urlStr containsString:@"http"]) {
                            urlStr = [NSString stringWithFormat:@"https://storage.googleapis.com/meboo-online-b68e7.appspot.com%@",urlStr];
                        }
                        [self getVideoFirstViewImage:urlStr];
                    } else {
                        [weakSelf preLoadImageWithUrl:urlStr];
                    }
                    if (self.sendBlock) {
                        self.sendBlock(YES);
                    }
                }
            }];
        }
    }];
}

- (void)preLoadImageWithUrl:(NSString *)urlStr {
    if (![urlStr containsString:@"http"]) {
        urlStr = [NSString stringWithFormat:@"https://storage.googleapis.com/meboo-online-b68e7.appspot.com%@",urlStr];
    }
    [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:urlStr] options:SDWebImageRetryFailed progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
    }];
}

// 存储视频第一帧
- (void)getVideoFirstViewImage:(NSString *)videoURL{
//    __WeakSelf
    NSString *url = [NSString stringWithFormat:@"%@?flag=2",videoURL];
    __block UIImage *videoImage;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL URLWithString:url] options:nil];
        NSParameterAssert(asset);
        AVAssetImageGenerator *assetImageGenerator =[[AVAssetImageGenerator alloc] initWithAsset:asset];
        assetImageGenerator.appliesPreferredTrackTransform = YES;
        assetImageGenerator.apertureMode =AVAssetImageGeneratorApertureModeEncodedPixels;
        CGImageRef thumbnailImageRef = NULL;
        NSError *thumbnailImageGenerationError = nil;
        thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(0, 60)actualTime:NULL error:&thumbnailImageGenerationError];
        if(!thumbnailImageRef)
            NSLog(@"thumbnailImageGenerationError %@",thumbnailImageGenerationError);
        videoImage = thumbnailImageRef ? [[UIImage alloc]initWithCGImage:thumbnailImageRef]: nil;
        [[SDImageCache sharedImageCache] storeImage:videoImage forKey:videoURL toDisk:YES completion:^{
            
        }];
        
    });
}

#pragma mark - Public Metohd
//1Mb=1024×1024b=1048567b。
- (void)setVideoLength:(NSInteger)videoLength {
    _videoLength = videoLength;
    if (videoLength > 0 && self.curPhoto.videoAsset) {
        [[PHImageManager defaultManager] requestAVAssetForVideo:self.curPhoto.videoAsset options:nil resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
            AVURLAsset *asset0 = (AVURLAsset *)asset;
            self.videoSize =  [NSData dataWithContentsOfURL:asset0.URL].length/1048567;//convert to MB
        }];
    }
}

- (void)setIsFromAlum:(BOOL)isFromAlum {
    _isFromAlum = isFromAlum;
    self.topBackView.hidden = !isFromAlum;
    self.bottomBackView.hidden = !isFromAlum;
}

#pragma mark - Action
- (void)closeAction {
    self.topBackView.hidden = YES;
    self.bottomBackView.hidden = YES;
    [self dismiss];
}

- (void)sendAction {
    
    if (self.videoLength >60) {
        self.videoLength = 0;
        [MBProgressHUD showInfoMessage:@"Please be less than 60s"];
        return;
    }
    
    if (self.videoLength <1) {
        [MBProgressHUD showInfoMessage:@"Please be more than 1s"];
        return;
    }
    
    if (self.videoSize > 50) {
        self.videoSize = 0;
        [MBProgressHUD showInfoMessage:@"Please be less than 50m"];
        return;
    }
    
    if (self.videoLength > 0) {
        [self.curPhotoView.player gk_stop];
    }
    __WeakSelf
    [MBNotificationCenter postNotificationName:REGISTER_UPLOADPHOTO_BEGIN object:nil];
    if (self.curPhoto.isVideo) {
        [[PHImageManager defaultManager] requestAVAssetForVideo:self.curPhoto.videoAsset options:nil resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
            AVURLAsset *asset0 = (AVURLAsset *)asset;
             weakSelf.data = [NSData dataWithContentsOfURL:asset0.URL];
            dispatch_async(dispatch_get_main_queue(), ^{
                // 非主线程，将UI操作切换到主线程进行
                [weakSelf putUploadImageOrVideo:YES];
            });
        }];
    } else {
        [self putUploadImageOrVideo:NO];
    }
    
    [self closeAction];
}

- (UIView *)getBgView{
    UITextField *bgTextField = [[UITextField alloc] init];
    [bgTextField setSecureTextEntry:true];
    
    UIView *bgView = bgTextField.subviews.firstObject;
    [bgView setUserInteractionEnabled:true];
    bgView.backgroundColor = UIColor.clearColor;
    return bgView;
}

#pragma mark - UI
- (void)creatSubViews {
    
    for (UIView *view in self.view.subviews) {
        CGRect frame = view.frame;
        [view removeFromSuperview];
        [self.secView addSubview:view];
        view.frame = frame;
    }
    
    [self.view addSubview:self.secView];
    [self.view sendSubviewToBack:self.secView];
    [self.secView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self.secView addSubview:self.topBackView];
    [self.topBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.mas_equalTo(MBHeightScale(50));
        make.height.mas_equalTo(MBHeightScale(50));
    }];
    
    [self.topBackView addSubview:self.closeBtn];
    [self.closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.topBackView);
        make.left.mas_equalTo(MBWidthScale(10));
        make.width.height.mas_equalTo(MBHeightScale(25));
    }];
    
    [self.secView addSubview:self.bottomBackView];
    [self.bottomBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.bottom.mas_equalTo(MBHeightScale(-50));
        make.height.mas_equalTo(MBHeightScale(50));
    }];
    
    [self.bottomBackView addSubview:self.sendBtn];
    [self.sendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.bottomBackView);
        make.right.mas_equalTo(MBWidthScale(-10));
        make.height.mas_equalTo(MBHeightScale(32));
        make.width.mas_equalTo(MBHeightScale(72));
    }];
    
    CGRect rect = self.progressView.frame;
    rect = CGRectMake(rect.origin.x, ScreenHeight-MBHeightScale(150), rect.size.width, rect.size.height);
    self.progressView.frame = rect;
}

#pragma mark - Setter && Getter

- (UIView *)topBackView {
    if (!_topBackView) {
        _topBackView = [UIView new];
        _topBackView.tag = 1001;
        _topBackView.backgroundColor = [UIColor colorWithRed:0 / 255.0 green:0 / 255.0 blue:0 / 255.0 alpha:0.5];
    }
    return _topBackView;
}
- (UIButton *)closeBtn {
    if (!_closeBtn) {
        _closeBtn = [[UIButton alloc] init];
        [_closeBtn setYXEnlargeEdgeWithTop:10 right:10 bottom:10 left:10];
        [_closeBtn setImage:ImageWithName(@"flash_chat_close") forState:0];
        [_closeBtn addTarget:self action:@selector(closeAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _closeBtn;
}

- (UIView *)bottomBackView {
    if (!_bottomBackView) {
        _bottomBackView = [UIView new];
        _bottomBackView.tag = 1002;
        _bottomBackView.backgroundColor = [UIColor colorWithRed:0 / 255.0 green:0 / 255.0 blue:0 / 255.0 alpha:0.5];
    }
    return _bottomBackView;
}

- (UIButton *)sendBtn {
    if (!_sendBtn) {
        _sendBtn = [[UIButton alloc] init];
        [_sendBtn setYXEnlargeEdgeWithTop:10 right:10 bottom:10 left:10];
        [_sendBtn setBackgroundColor:HEXS(@"B92176")];
        _sendBtn.layer.cornerRadius = MBHeightScale(16);
        [_sendBtn setTitle:@"Done" forState:0];
        _sendBtn.titleLabel.font = PDBoldScale(18);
        [_sendBtn setTitleColor:HEXS(@"ffffff") forState:0];
        [_sendBtn addTarget:self action:@selector(sendAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sendBtn;
}

- (NSData *)data {
    if (!_data) {
        _data = [NSData data];
    }
    return _data;
}

- (UIView *)secView {
    if (!_secView) {
        _secView = [self getBgView];
    }
    return _secView;
}
@end
